package com.tulele.vtool.handler;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tulele.vtool.utils.AesExpand.aesDecrypt;
import static com.tulele.vtool.utils.AesExpand.aesEncrypt;

/**
 * 海报信息表(BPosterInfo)表控制层
 *
 * @author makejava
 * @since 2020-11-27
 */
@Slf4j
@RestController
@RequestMapping("bPosterInfo")
public class BPosterInfoHandler {
    /**
     * 服务对象
     */
    @Autowired
    private BPosterInfoService bPosterInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    /**
     * 服务对象
     */
    @Autowired
    private BPosterDetailsService bPosterDetailsService;

    @Autowired
    private BPosterHistoryService bPosterHistoryService;

    @Autowired
    private IUserPromotionSettleInfoService userPromotionSettleInfoService;

    /**
     * 查询多条数据
     * 127.0.0.1:8070/bPosterInfo/selectAllByLimit
     *
     * @param bPosterInfo 实例对象
     * @return 实例对象
     */
    @PostMapping(value = "/selectAllByLimit", produces = "application/json;charset=UTF-8")
    public RespData selectAllByLimit(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody BPosterInfo bPosterInfo) {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive) || bPosterInfo == null || bPosterInfo.getType() == null) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer pageNum = bPosterInfo.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            bPosterInfo.setPageNum(1);
        }

        Integer pageSize = bPosterInfo.getPageSize();
        if (pageSize == null || pageSize.intValue() <= 0) {
            bPosterInfo.setPageSize(10);
        }

        bPosterInfo.setGzhCode(springProfilesActive);
        PageInfo<BPosterInfo> pageInfo = this.bPosterInfoService.selectAllByLimit(bPosterInfo);

        if (null == pageInfo.getList() || pageInfo.getList().size() <= 0) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("暂无更多");
            return respData;
        }

        List<BPosterInfo> queryAllByLimitDto = pageInfo.getList();

        if (CollectionUtils.isNotEmpty(queryAllByLimitDto)) {
            List<BPosterInfo> collect = queryAllByLimitDto.stream().map(info -> {
                try {
                    BPosterInfo temporary = new BPosterInfo();

                    // 加密id
                    temporary.setInfoKey(aesEncrypt(info.getId().toString(), SysConstant.KEY));
                    temporary.setCover(info.getCover());
                    temporary.setMember(info.getMember());

                    return temporary;
                } catch (Exception e) {
                    e.printStackTrace();

                    return null;
                }
            }).collect(Collectors.toList());

            Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
            resultMap.put("msg", pageInfo.isIsLastPage());
            resultMap.put("collect", collect);

            respData.setData(resultMap);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("查询成功");
            return respData;
        }

        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg("暂无更多");
        return respData;
    }

    /**
     * 通过主键查询单条数据
     * 127.0.0.1:8070/bPosterInfo/selectOne?infoKey=bGQc/qZTg1blPBfrAqCfmA==
     *
     * @param infoKey 主键
     * @return 单条数据
     */
    @GetMapping(value = "/selectOne", produces = "application/json;charset=UTF-8")
    public RespData selectOne(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @Param("infoKey") String infoKey) throws Exception {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive) || StringUtils.isBlank(infoKey)) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer userIdInt = Integer.valueOf(userId);

        // 解密id
        Integer idInt = Integer.valueOf(aesDecrypt(infoKey, SysConstant.KEY));

        BPosterInfo info = this.bPosterInfoService.queryById(idInt);
        BPosterInfo temporary = new BPosterInfo();

        // 加密id
        temporary.setInfoKey(aesEncrypt(info.getId().toString(), SysConstant.KEY));
        temporary.setCover(info.getCover());
        temporary.setMember(info.getMember());

        List<BPosterDetails> items = this.bPosterDetailsService.queryItemByTYpe(idInt);
        Integer hasHeard = 0;
        Integer hasName = 0;
        Integer hasPhone = 0;
        Integer hasComp = 0;
        Integer hasText1 = 0;
        Integer hasText2 = 0;
        Integer hasText3 = 0;


        for (BPosterDetails e: items) {
            if(e.getItem() == 1012){
                hasHeard = 1;
            }

            if(e.getItem() == 1015){
                hasName = 1;
            }

            if(e.getItem() == 1016){
                hasPhone = 1;
            }

            if(e.getItem() == 1017){
                hasComp = 1;
            }

            if(e.getItem() == 1018){
                hasText1 = 1;
            }

            if(e.getItem() == 1019){
                hasText2 = 1;
            }

            if(e.getItem() == 1020){
                hasText3 = 1;
            }
        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(9);
        resultMap.put("userInfo", userInfoService.getUserInfo(userIdInt));
        resultMap.put("bPosterInfo", temporary);
        resultMap.put("hasHeard", hasHeard);
        resultMap.put("hasName", hasName);
        resultMap.put("hasPhone", hasPhone);
        resultMap.put("hasComp", hasComp);
        resultMap.put("hasText1", hasText1);
        resultMap.put("hasText2", hasText2);
        resultMap.put("hasText3", hasText3);

        respData.setData(resultMap);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("查询成功");
        return respData;

    }

    /**
     * 合成海报
     *
     * @param bPosterInfo 实例对象
     * @return 单条数据
     */
    @PostMapping(value = "/creatByInfoKey", produces = "application/json;charset=UTF-8")
    public RespData creatByInfoKey(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive, @RequestBody BPosterInfo bPosterInfo) throws Exception {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive) || bPosterInfo == null || StringUtils.isBlank(bPosterInfo.getInfoKey())) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);

        String result = this.bPosterInfoService.creatByInfoKey(userId, springProfilesActive, bPosterInfo);

        if (StringUtils.isNotBlank(result) && result.contains(SysConstant.CREAT_POSTER_PICTURE_OSS_ACCESS_PREFIX + SysConstant.CREAT_POSTER_PICTURE_OSS_DIR + userId)) {

            resultMap.put("result", result);
            respData.setData(resultMap);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("海报生成成功");
            return respData;
        }

        resultMap.put("result", "");
        respData.setData(resultMap);
        respData.setCode(ReturnCode.CLIENT_ERROR);
        respData.setMsg(result);
        return respData;
    }

    /**
     * 获取用户的海报列表
     * @param userId 用户 ID
     * @param springProfilesActive 公众号标识
     * @return 海报列表
     */
    @PostMapping(value = "/getUserPoster", produces = "application/json;charset=UTF-8")
    public RespData getUserPoster(@RequestHeader("userId") String userId, @RequestHeader("identifying") String springProfilesActive) {
        RespData respData = new RespData();

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(springProfilesActive)) {
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
        }

        // 1、查看用户是否有海报记录
        List<BPosterHistory> userPosterHistoryList = bPosterHistoryService.getUserPosterHistory(Integer.valueOf(userId), springProfilesActive);

        if (CollectionUtils.isNotEmpty(userPosterHistoryList)) { // 如果存在
            HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
            List<String> userPosterList = new ArrayList<>();
            String msg = "";

            // 获取用户头像、名称以及二维码
            UserInfo userInfo = userInfoService.getUserInfo(Integer.valueOf(userId));

            String nickName = userInfo.getNickName();// 昵称
            String avatarUrl = userInfo.getAvatarUrl();// 头像
            String telNum = userInfo.getTelNum();// 电话

            // 提示用户要完善的信息
            msg += StringUtils.isBlank(nickName) ? "昵称、" : "";
            msg += StringUtils.isBlank(avatarUrl) ? "头像、" : "";
            msg += StringUtils.isBlank(telNum) ? "电话、" : "";
            if (StringUtils.isNotBlank(msg)) {
                msg = msg.substring(0, msg.length() - 1);
                msg += ",不能为空";
            } else {
                msg += "成功";
            }

            for (BPosterHistory bPosterHistory : userPosterHistoryList) {
                if (StringUtils.isNotBlank(bPosterHistory.getResult())) {// 如果链接存在，直接加入数组
                    userPosterList.add(bPosterHistory.getResult());
                } else {// 如果不存在或过期，则重新生成
                    BPosterInfo info = new BPosterInfo();
                    info.setId(bPosterHistory.getId());// 这里只是把 ID 暂时寄存在 bPosterHistory 中
                    info.setPosterName(nickName);
                    info.setPosterHeard(avatarUrl);
                    info.setPosterPhone(telNum);

                    try {
                        String userPoster = bPosterInfoService.getUserPosterList(userId, springProfilesActive, info);
                        userPosterList.add(userPoster);
                    } catch (Exception e) {
//                        e.printStackTrace();
                    }
                }
            }

            // 获取用户的推广总收益
            UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoService.getUserPromotionSettleInfo(Integer.valueOf(userId));

            resultMap.put("userCumulativeIncome", userPromotionSettleInfo.getCumulativeIncome());
            resultMap.put("userPosterList", userPosterList);

            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg(msg);
            respData.setData(resultMap);
        } else {// 如果不存在
            respData.setCode(ReturnCode.SERVER_ERROR);
            respData.setMsg("公众号还未设置海报");
        }

        return respData;
    }
}